package com.san;

import java.io.File;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class TestPDF {

	public static void main(String[] args) {
		try {
//			test();
			TestPDF t = new TestPDF();
			t.convert("http://credit.hangzhou.gov.cn/home/home.html", "D:\\dytest\\test11.pdf");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void test() throws Exception {
		// Step 1—Create a Document.
		// 页面大小
		Rectangle rect = new Rectangle(PageSize.A4.rotate());
		// 页面背景色
//		rect.setBackgroundColor(BaseColor.ORANGE);  

		Document doc = new Document(rect);
		BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		Font font = new Font(bf, 6, Font.NORMAL, BaseColor.WHITE);
		Chunk id = new Chunk("chinese", font);
		id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
		id.setTextRise(6);
		doc.add(id);
		doc.add(Chunk.NEWLINE);

		PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("D:\\dytest\\mytest.pdf"));

		writer.setPageEvent(new PdfPageEventHelper() {

			public void onEndPage(PdfWriter writer, Document document) {

				PdfContentByte cb = writer.getDirectContent();
				cb.saveState();

				cb.beginText();
				BaseFont bf = null;
				try {
					bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
				} catch (Exception e) {
					e.printStackTrace();
				}
				cb.setFontAndSize(bf, 10);

				// Header
				float x = document.top(-20);

				// 左
				cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "企业基础信用报告AAA", document.left(), x, 0);
				// 右
				cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "联系电话：400-029-1688", document.right(), x, 0);
				Image header_split = null;
				try {
					header_split = Image.getInstance("D:\\dytest\\header_split.jpg");
					cb.addImage(header_split);
				} catch (Exception e) {
					e.printStackTrace();
				}

				// Footer
				float y = document.bottom(-20);

				Image footer_split = null;
				Image footer_logo = null;
				try {

					footer_split = Image.getInstance("D:\\dytest\\footer_split.jpg");
					cb.addImage(footer_split);
					footer_logo = Image.getInstance("D:\\dytest\\footer_logo.png");
					cb.addImage(footer_logo);
				} catch (Exception e) {
					e.printStackTrace();
				}

				// 左
				cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
						"本报告仅供商业决策参考之用，不得作为法律诉讼的依据；未经同意和授权，不得向第三人透露本报告任何内容；在任何情况下，对由于使用本报告所造成的损失，本公司不承担任何责任。",
						document.left(), y, 0);
//				// 中
//				cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber() + " page",
//						(document.right() + document.left()) / 2, y, 0);
//				// 右
//				cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "F-Right", document.right(), y, 0);

				cb.endText();

				cb.restoreState();
			}
		});

		doc.open();
		doc.add(new Paragraph("1 page"));
		doc.newPage();
//		doc.add(new Paragraph("2 page"));
//		doc.newPage();
//		doc.add(new Paragraph("3 page"));
//		doc.newPage();
//		doc.add(new Paragraph("4 page"));

		doc.close();
	}

	/**
	 * 执行PDF生成
	 * 
	 * @param srcPath
	 * @param destPath
	 * @return
	 */
	public static String convert(String srcPath, String destPath) {
		File file = new File(destPath);
		File parent = file.getParentFile();
		// 如果pdf保存路径不存在，则创建路径
		if (!parent.exists()) {
			parent.mkdirs();
		}

		StringBuilder cmd = getFormal();

		// html路径 即目标网页路径
		cmd.append(" ");
		cmd.append(srcPath);
		cmd.append(" ");
		// pdf保存路径
		cmd.append(destPath);

		String result = "1";
		try {
			Process proc = Runtime.getRuntime().exec(cmd.toString());
			HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
			HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
			error.start();
			output.start();
			proc.waitFor();
		} catch (Exception e) {
			result = "2";
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 标准格式
	 *
	 * @return
	 */
	public static StringBuilder getFormal() {
		StringBuilder cmd = new StringBuilder();
		// wkhtmltopdf 在系统中的路径
		cmd.append("D:\\dytest\\wkhtmltopdf\\bin\\wkhtmltopdf.exe");
		// cmd.append(" ");

		cmd.append(" --header-line");// 页眉下面的线
		cmd.append("  --footer-line");// 页脚上面的线
		cmd.append("  --footer-center [page]/[topage]"); // 在页脚中心放置页码
		// cmd.append(" --header-right 这里是我们系统的页眉"); // 页眉中间放置文字
		cmd.append("  --header-html http://www.jdcredit.gov.cn/home/index.html"); // 页眉中间放置图片
		cmd.append("  --header-spacing 5 ");// (设置页眉和内容的距离,默认0 )
		cmd.append("  --margin-top 20mm  "); // 设置页面上边距 (default 10mm)
		// cmd.append(" cover http://localhost:8090/firstPage.html ");
		return cmd;
	}

}
